package org.jeecg.modules.cosmetic.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.cosmetic.constant.enums.ProductStatusEnum;
import org.jeecg.modules.cosmetic.entity.TProduct;
import org.jeecg.modules.cosmetic.mapper.TProductMapper;
import org.jeecg.modules.cosmetic.service.ITProductService;
import org.jeecg.modules.cosmetic.utils.AuthInfo;
import org.jeecg.modules.cosmetic.utils.CurrentUserUtil;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.Objects;
import java.util.Optional;

/**
 * @Description: t_product
 * @Author: jeecg-boot
 * @Date: 2022-06-30
 * @Version: V1.0
 */
@DS("cosmetic-datasource")
@Service
public class TProductServiceImpl extends ServiceImpl<TProductMapper, TProduct> implements ITProductService {

    /**
     * 初始化产品信息
     *
     * @return
     */
    @Override
    public Long createProduct(Long productId) {
        if (productId != null){
            TProduct product = new TProduct();
            product.setId(productId);
            product.setStatus(ProductStatusEnum.DELETE.getCode());
            this.updateById(product);
        }
        TProduct tProduct = this.getOne(new LambdaQueryWrapper<TProduct>()
                .orderByDesc(TProduct::getAutoCode).last("limit 1"));
        Integer num = 1;
        if (!Objects.isNull(tProduct)) {
            num = Integer.valueOf(tProduct.getAutoCode());
            num++;
        }
        String idx = StringUtils.leftPad(String.valueOf(num), 4, "0");
        String sysCode = String.format("CFP(C)%s%s", DateUtils.getDate("yyyy"), idx);
        AuthInfo authInfo = CurrentUserUtil.authInfo();
        Optional.ofNullable(authInfo).orElseThrow(() -> new JeecgBootException("用户非法"));
        TProduct product = new TProduct()
                .setSysCode(sysCode)
                .setOriginSysCode(sysCode)
                .setCreateBy(authInfo.getName())
                .setUpdateBy(authInfo.getName())
                .setAutoCode(idx);
        boolean flag = this.save(product);
        return flag ? product.getId() : 0L;
    }
}
